# -*- conding:UTF-8 -*-

'''
@ Project: news
@ File: user.py
@ Author: 韩成瑾
@ Date：2022/7/28 9:06

'''
import redis
from flask import Blueprint, jsonify, make_response, request, g
from flask_restful import Resource, Api, reqparse
from models.model import *

student_bp = Blueprint('student_bp', __name__, url_prefix='/student')

api = Api(student_bp)



# 学生登陆
class Student_login(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('phone')
        req.add_argument('password')
        args = req.parse_args()

        student = Student.query.filter(Student.phone == args['phone'] and Student.password == args['password']).one()
        print(student)
        if student.id:
            resp = make_response("学生id 登录状态模拟")
            resp.set_cookie("student_id", str(student.id), max_age=36000)
            return resp
        return jsonify({
            'code':400
        })



class Student2teacherView(Resource):
    def put(self):
        req = reqparse.RequestParser()
        req.add_argument('teacher_id')
        args = req.parse_args()
        teacher_id = args['teacher_id']
        student_id = request.cookies.get("student_id")
        if not student_id:
            return jsonify({
                'code':403,
                'msg':'请登录'
            })
        teacher = Teacher.query.filter(Teacher.id == teacher_id).one()
        student = Student.query.filter(Student.id == student_id).one()
        if teacher.students:
            return jsonify({
                'code':400,
                'msg':'已经关注啦'
            })

        teacher.students.append(student)
        teacher.attention_num += 1
        db.session.commit()
        return jsonify({
            'code':200,
            'msg':'关注成功'
        })


# 密码
class Password(Resource):
    # 修改密码
    def put(self,id):
        req = reqparse.RequestParser()
        req.add_argument('id')
        req.add_argument('password')
        args = req.parse_args()

        






        Student.query.filter(Student.id == id).update(args)
        db.session.commit()
        return jsonify({
            'code': 200, 'msg': '重置密码成功'
        })


    # 重置密码
    def post(self):
        stu_id = g.stu_id

        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        parser.add_argument('password')
        parser.add_argument('sms_code')
        parser.add_argument('pwd')

        args = parser.parse_args()

        phone = args.get('mobile')
        password = args.get('password')
        code = args.get('sms_code')
        pwd = args.get('pwd')

        if not all([phone, code, password]):
            return jsonify({'信息不完整'})

        stu = Student.query.filter_by(id=stu_id).first()
        print('stu:', stu)
        if phone != stu.phone:
            return jsonify({'msg': '手机号不正确', 'code': 204})

        smscode = redis.Redis(db=5, host='localhost', password=123456, port=6379).get(phone)
        print('redis:', smscode)

        if not smscode:
            return jsonify({'message': '验证码已过期!', 'code': 204})
        print('验证码：', code)

        # 当取出来的值和code不相等时
        if smscode.decode() != code:  # 在redis中存进去的值为字符类型，但是取出来是字节类型的，所以需要decode来进行解码
            return jsonify({'message': '验证码错误!', 'code': 204})
        print('前端:', code, 'redis:', smscode)

        if password != stu.password:
            return jsonify({'msg': '密码不正确', 'code': 204})

        student = Student.query.filter_by(id=stu_id)
        if student:
            student.update({'password': pwd})

        db.session.commit()
        return jsonify({'msg': '操作成功', 'code': 200, 'data': 1})














class StudentsView(Resource):
    # 展示所有学生
    def get(self):
        student_all = Student.query.all()
        student_list = []
        for student in student_all:
            a = {
                'id':student.id,
                'name':student.name,
                'password':student.password,
                'info':student.info,
                'status':student.status,
                'money':float(student.money),
            }
            student_list.append(a)
        return jsonify({
            'code':200,
            'list':student_list
        })


    # 增加学生
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('name')
        req.add_argument('phone')
        req.add_argument('password')
        req.add_argument('info')
        args = req.parse_args()

        student = Student(name=args['name'],phone=args['phone'],password=args['password'],info=args['info'])
        db.session.add(student)
        db.session.commit()

        return jsonify({
            'code':200,'msg':'添加成功'
        })


class StudentView(Resource):
    # 展示一条数据
    def get(self,id):
        student_one = Student.query.filter(Student.id==id).one()
        student_one_list = {
            'id':student_one.id,
            'name':student_one.name,
            'phone':student_one.phone,
            'password':student_one.password,
            'info':student_one.info
        }
        return jsonify({
            'code':200,
            'list':student_one_list
        })


    # 修改学生信息
    def put(self,id):
        req = reqparse.RequestParser()
        req.add_argument('name')
        req.add_argument('phone')
        req.add_argument('password')
        req.add_argument('info')
        args = req.parse_args()

        student_info = Student.query.filter(Student.id==id).first()
        if not student_info:
            return jsonify({
                'code':400,'msg':'没有这个学生'
            })

        Student.query.filter(Student.id==id).update(args)
        db.session.commit()
        return jsonify({
            'code':200,'msg':'修改成功'
        })

    # 删除学生信息
    def delete(self,id):
        req = reqparse.RequestParser()
        req.add_argument('id')
        args = req.parse_args()

        Student.query.filter(Student.id==id).delete()
        db.session.commit()

        return jsonify({
            'code':200,'msg':'删除成功'
        })




api.add_resource(Student_login, 'student_login')
api.add_resource(Student2teacherView,'fllow_to_teacher')
api.add_resource(StudentsView,'/student')
api.add_resource(StudentView,'/student/<int:id>')
api.add_resource(Password,'/password/<int:id>')



